import React from "react";
import Button from 'antd/lib/button';
import Divider from 'antd/lib/divider';
import Menu from 'antd/lib/menu';
import Modal from 'antd/lib/modal';
import Enums from "@/services/enums";
import EmployeeChangeTable from "@/components/employee/EmployeeChangeTable";
import EmployeeChange from "@/services/employeechange";
import notification from "@/services/notification";
import {get} from "lodash";
import CheckDialog from "@/components/workflow/CheckDialog";
import {currentUser} from "@/services/auth";
import Workflow from "@/services/workflow";
import moment from "moment";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import {createBrowserHistory} from 'history';
const customHistory = createBrowserHistory();
const { confirm } = Modal;
export default class EmployeeChangeToolbar extends React.Component {
  state = {
    loading: true,
    isnew: true,
    id: 0,//
    userid: currentUser.id,//--操作员ID
    bill_date: moment(),//--申请日期
    code: "",//----职员编码
    name: "",//--职员名称
    major:[],//毕业专业
    area:"",//地区
    mobile:"",//手机号
    bytstatus:"洽谈中",
    status: 0,//--状态
    message: "",//--纪录事项
    openseapool:0,//是否公海池 0否；1是
    //===================
    isedit:true,
    isdel:true,
    allow_col:[],
    colcontrol:false,
    annex:[],//--附件
    employeechangedata:[],
    openpage:"jbxx",
    employeestatusdata:[],
    employeemajordata:[],
  };
  componentWillMount() {
    Enums.items("employeestatus").then(data => {
      this.setState({
        employeestatusdata: data,
      });
    });
    Enums.items("employeemajor").then(data => {
      this.setState({
        employeemajordata: data,
      });
    });

     if(this.props.id<1 || this.props.id===undefined ){
        EmployeeChange.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
        });
      });
     }else{
        this.setState({
          id: this.props.id,
          isnew: false,
          loading: false,
        });
       this.iseditData(this.props.id);
       this.refreshData(this.props.id) ;
     }
  }
  refreshData(id) {

    EmployeeChange.get({id: id}).then(data => {
      if (data.id > 0) {
        this.setState({
          id: data.id,//
          userid: data.userid,//--操作员ID
          bill_date: moment(data.bill_date),//--申请日期
          code: data.code,//----编号
          name: data.name,//--名称
          major: data.major,
          area: data.area,
          mobile: data.mobile,//手机号
          bytstatus: data.bytstatus,
          status: data.status,//--状态
          message: data.message,//--纪录事项
          openseapool:data.openseapool,//是否公海池 0否；1是
          loading: false,
        });
      } else {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          code: "",//----编号
          name: "",//--名称
          major: [],
          area: "",
          mobile: "",//手机号
          bytstatus: "洽谈中",
          status: 0,//--状态
          message: "",//--纪录事项
          openseapool:0,
        });
      }
    }).catch(error => {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          code: "",//----编号
          name: "",//--名称
          major: [],
          area: "",
          mobile: "",//手机号
          bytstatus: "洽谈中",
          status: 0,//--状态
          message: "",//--纪录事项
          openseapool:0,
        });
      });
}
  handleadd = () => {
    EmployeeChange.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
          isedit:true,
          isdel:true,
        });
        this.refreshData(data[0].id)
      });
  };
  ///|| str.match(/^[\s]*$/)
  isEmptyobj = (str) => {
	if(str==='' || str === null || str === 'null' || str === undefined || str === 'undefined'){
		return true;
	}else{
		return false;
	}
}
  handleSave = () => {
    let id = this.state.id;
    let userid = this.state.userid;
    let bill_date = this.state.bill_date;
    let code =  this.state.code;
    let name =  this.state.name;
    let major =  this.state.major;
    let area =  this.state.area;
    let mobile =  this.state.mobile;
    let bytstatus  =  this.state.bytstatus;
    let status =  this.state.status;
    let message =  this.state.message;
    let openseapool = this.state.openseapool;
    let annexchd = this.state.annex;

    if(this.state.openpage==="jbxx"){
       id = this.child.state.id;
       userid = this.child.state.userid;
       bill_date = this.child.state.bill_date;
       code =  this.child.state.code;
       name =  this.child.state.name;
       major =  this.child.state.major;
       area =  this.child.state.area;
       mobile =  this.child.state.mobile;
       bytstatus  =  this.child.state.bytstatus;
       status =  this.child.state.status;
       message =  this.child.state.message;
       openseapool = this.child.state.openseapool;
       annexchd = this.child.state.annex;

    }
    if(status ===0 && currentUser.id !==userid){
      notification.error("草稿状态，不是制单人，不能保存！");
      return;
    }
    if(status ===2){
      notification.error("已审批，不能保存！");
      return;
    }
    if(this.isEmptyobj(code)){
      notification.error("编号不能为空");
      return;
    }
    if(this.isEmptyobj(name)){
      notification.error("名称不能为空");
      return;
    }
    if(this.isEmptyobj(major)){
        notification.error("毕业专业不能为空");
        return;
    }
    if(this.isEmptyobj(area)){
    notification.error("区域不能为空");
    return;
    }
    let  annex=[]
    annexchd.forEach(file => {
      if(file.status==="done") {
         const b=[{
                  uid: file.uid,
                  name: file.name,
                  status: file.status,
                  bytstatus:file.bytstatus,
                  url: file.url
          }];
        if (annex.length < 1) {
          annex = b;
        } else {
          annex.push.apply(annex, b);
        }
      }
        });
    let data={
        id: id,//
        userid: userid,//--操作员ID
        bill_date: bill_date,//--申请日期
        code: code,//----编号
        name: name,//--名称
        major: major,
        area: area,
        mobile: mobile,
        bytstatus: bytstatus,
        status: status,//--状态
        message: message,
        openseapool: openseapool,
        annex: annex
    }
    if(this.state.isnew) {
        EmployeeChange.create(data)
        .then(() => {
          this.setState({
            isnew: false,
            loading: false,
            isedit: true,
            id: data.id,//
            userid: data.userid,//--操作员ID
            bill_date: data.bill_date,//--申请日期
            code: data.code,//----编号
            name: data.name,//--名称
            major: data.major,
            area: data.area,
            mobile: data.mobile,
            bytstatus: data.bytstatus,
            status: data.status,//--状态
            message: data.message,
            openseapool: data.openseapool,
            annex: data.annex,
          });
          notification.success("人员资料新增成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
        EmployeeChange.save(data)
        .then(() => {
          notification.success("人员资料修改成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }
  };
  handleDelete = () => {
    if(this.child.state.status !==0){
      notification.error("不是草稿状态，不能删除！");
      return;
    }
    confirm({
      title: '确定删除人员资料?',
      icon: <WarningOutlined />,
      content: this.child.state.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        EmployeeChange.delete({id: this.state.id}).then(()=>{
          notification.success("人员资料删除成功.");
          EmployeeChange.getid({id: 0}).then(data => {
              this.setState({
                id: data,
                isnew: true,
                loading: false,
                isedit: true,
              });
              this.refreshData(data);
            });
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  iseditData(id) {
      let item = {
        bill: "employeechange",
        billtype:this.state.openseapool,
        billid: id,
        userid: currentUser.id
      }
      Workflow.edit(item).then(data => {
        if(data.length>0){
              this.setState({
                isedit: data[0].edit,
                isdel: data[0].del,
                allow_col:data[0].allow_col,
                colcontrol:data[0].colcontrol,
              });
        }
      }).catch(error => {
              this.setState({
                isedit: true,
                isdel: true,
                allow_col:[],
                colcontrol:false,
              });
        });
  };
  handlebackpage= () => {
    customHistory.goBack();
  };
  handleCheck = () => {
    if(!currentUser.isAudit){
      notification.error("没有权限.");
      return;
    }
    let item={
      bill:"employeechange",
      id:this.state.id,
      message:"",
      status: this.child.state.status,
      altermsg: "",
    }
    if(this.state.status===0){
      item = {
        bill: "employeechange",
        billid: this.state.id,
        next_type: 1,
        message:'<div>同意</div>',
        userid: currentUser.id,
        billdate: this.state.bill_date.format('YYYY-MM-DD'),
        orgunitid:0,
        altermsg: "",
      }
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          this.iseditData(this.state.id);
          this.refreshData(this.state.id);
          notification.success(data[0].message);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
      CheckDialog.showModal({bill_check: item})
      .onClose((result = {}) => {
          if (result.success) {
            this.iseditData(this.state.id);
            this.refreshData(this.state.id);
          }
        }).onDismiss(() => {
        });
      }
  };
  tabsClick = e => {
    this.setState({
      openpage: e.key,
    });
  };
  render() {
    if (this.state.loading) return null;
    const data={
      id: this.state.id,//
      userid: this.state.userid,//--操作员ID
      code: this.state.code,//----编号
      name: this.state.name,//--名称
      major: this.state.major,
      area: this.state.area,
      mobile: this.state.mobile,
      bytstatus: this.state.bytstatus,
      status: this.state.status,//--状态
      message: this.state.message,//--纪录事项
      openseapool: this.state.openseapool,
      annex:this.state.annex,
    };
    return(
      <div>
        <div style={{ marginBottom: 16 }}>
        <Button type="primary" style={{margin:"10px"}} onClick={() => this.handlebackpage()}>
            <i className="fa fa-reply m-r-5" />
            返回
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleadd()}>
            <i className="fa fa-plus m-r-5" />
            新增
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleSave()} disabled ={!this.state.isedit}>
            <i className="fa fa-save m-r-5" />
            保存
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleDelete()} disabled ={!this.state.isdel}>
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleCheck()}>
            <i className="fa fa-check m-r-5" />
            {this.state.status===0 ? "提交":"审核"}
          </Button>
        </div>
        <div>
          <Menu onClick={this.tabsClick} selectedKeys={this.state.openpage} mode="horizontal">
                  <Menu.Item key = "jbxx">基本信息</Menu.Item>
          </Menu>
          <EmployeeChangeTable data={data}  isedit={this.state.isedit}  isnew={this.state.isnew} 
          allow_col={this.state.allow_col} colcontrol={this.state.colcontrol}
          employeestatusdata={this.state.employeestatusdata} employeemajordata={this.state.employeemajordata}
          onRef={(ref) => { this.child = ref; }} />
        </div>
      </div>
    );
  };
}